﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using PSAMMatrixCloud.Common;
using PSAMMatrixCloud.Model;
using PSAMMatrixCloud.TransferSecret.PSAMMatrix;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace PSAMMatrixCloud.PSAMSecret
{
    class Program
    {
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogHelper.Error($"未捕获异常,sender:{sender},args:{e.ExceptionObject}");
        }

        static async Task  Main(string[] args)
        {
            System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            var builder = new HostBuilder()
             .ConfigureAppConfiguration((hostContext, configApp) =>
             {
                 configApp.SetBasePath(AppContext.BaseDirectory);
                 configApp.AddJsonFile("appsettings.json", optional: true);
             })
             .ConfigureServices((hostContext, services) =>
             {
                  //配置Settings
                  hostContext.Configuration.LoadSettings<ConnectionStrings>();
                  hostContext.Configuration.LoadSettings<PSAMSeetings>();


                 if (Debugger.IsAttached)
                 {
                     try
                     {
                         PSAMSocket.Start();//启动与psam加密盒子通讯服务
                         PSAMMatrixCloud.TransferSecret.LaneMutual.LaneServer.RunAsync().Wait();//启动云端车道后台服务
                     }
                     catch (Exception ex)
                     {
                         Console.WriteLine(ex);
                     }

                     while (true)
                     {
                         Console.ReadLine();
                     }
                 }
                 else
                 {

                     PMSScecretService.RunAsService();
                 }
             });

            var isService = !(Debugger.IsAttached || args.Contains("--console")); //Debug状态或者程序参数中带有--console都表示普通运行方式而不是Windows服务运行方式
            if (isService)
            {
                await builder.RunAsServiceAsync();
            }
            else
            {
                await builder.RunConsoleAsync();
            }

        }

     
    }
}
